<template>
    <div>
        <Headline
                :headline1="$t('m.SystemManagement') + '  /  '"
                :headline2="$t('m.RegionalAuthorized')"
        />
        <a-card style="width: 100%">
            <a-tree-select
                    class="select-tree"
                    style="width: 200px; margin-right: 15px"
                    @change="argumentSelect"
                    v-model="defaultSelect"
                    show-search
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :placeholder="$t('m.pleaseChoose')"
                    allow-clear
                    tree-default-expand-all
            >
                <a-tree-select-node
                        v-for="item in data"
                        :key="item.id"
                        :cont="item"
                        :value="item.areaname"
                        :title="item.areaname"
                >
                    <a-tree-select-node
                            v-for="int in item.children"
                            :key="int.id"
                            :cont="int"
                            :value="int.areaname"
                            :title="int.areaname"
                    >
                        <a-tree-select-node
                                v-for="ins in int.children"
                                :key="ins.id"
                                :cont="ins"
                                :value="ins.areaname"
                                :title="ins.areaname"
                        />
                    </a-tree-select-node>
                </a-tree-select-node>
            </a-tree-select>
            <a-button
                    type="primary"
                    @click="add"
                    icon="plus"
                    style="margin-right: 15px"
                    v-if="isTrue('sys:areaauth:add')"
            >
                {{ $t("m.Add") }}
            </a-button>
            <a-button
                    @click="inquire"
                    style="background-color: #67c23a; border-color: #67c23a; color: white"
                    icon="zoom-in"
                    v-if="isTrue('sys:areaauth:select')"
            >
                {{ $t("m.QueryAuthorization") }}
            </a-button>
            <a-table
                    size="small"
                    style="margin-top: 30px"
                    :columns="columns"
                    :rowKey="(record, i) => i"
                    :data-source="dataA"
                    :pagination="false"
                    bordered
            >
                <div slot="tags" slot-scope="text, tags, i">
                    <a-button
                            @click="delkey(text, tags, i)"
                            type="danger"
                            icon="delete"
                            :disabled="!isTrue('sys:menu:del')"
                    >{{ $t("m.Delete") }}
                    </a-button
                    >
                </div>
            </a-table>
            <a-pagination
                    style="margin-top: 20px"
                    show-size-changer
                    :default-current="1"
                    :total="total"
                    @change="Pages"
                    :pageSizeOptions="['5', '10', '30', '40']"
                    @showSizeChange="onShowSizeChange"
                    class="pages"
            />
        </a-card>
        <a-modal
                :title="$t('m.TheSecondaryAuthorization')"
                :visible="visible"
                @cancel="handleCancel"
                :cancelText="$t('m.Cancel')"
                :okText="$t('m.Ok')"
                @ok="handleOk"
        >
            <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                <a-form-item :label="$t('m.SelectArea')">
                    <a-input v-model="areaValue" disabled></a-input>
                </a-form-item>
                <a-form-item :label="$t('m.Subdomain')">
                    <a-checkbox @change="onChange"
                    >{{ $t("m.FullAutomaticAuthorization") }}
                    </a-checkbox>
                </a-form-item>
            </a-form>
            <a-input-search
                    v-model="forminitialA.key"
                    :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                    style="width: 300px"
                    enter-button
                    @search="onSearch"
            />
            <a-table
                    size="small"
                    style="margin-top: 20px"
                    :columns="columnsB"
                    :rowKey="(record, i) => i"
                    :data-source="dataB"
                    :pagination="false"
                    :row-selection="{
          onChange: onSelectChange,
          type: 'radio',
          selectedRowKeys: selectedRowKeysList,
        }"
                    bordered
            >
            </a-table>
            <a-pagination
                    style="margin-top: 20px"
                    show-size-changer
                    :default-current="1"
                    :total="totalA"
                    @change="PagesA"
                    :pageSizeOptions="['5', '10', '30', '40']"
                    @showSizeChange="onShowSizeChangeA"
                    class="pages"
            />
        </a-modal>
        <a-modal
                :title="$t('m.AdministratorLevel2AuthorizationQuery')"
                :visible="visibleB"
                @cancel="handleCancelB"
                :footer="null"
        >
            <a-input-search :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                            v-model="forminitialC.key"
                            style="width:150px;margin-right:15px"
                            enter-button @search="onSearchA"/>
            {{$t('m.SystemUser')}}：
            <a-select style="width: 120px;margin-right:15px;"
                      v-model="forminitialC.userId"
                      @change="handleChange">
                <a-select-option
                        :value="item.userid"
                        v-for="item in dataB"
                        :key="item.userid"
                >
                    {{ item.nickname }}
                </a-select-option>
            </a-select>

            <a-button type="danger" @click="del" icon="delete">{{$t('m.Delete')}}</a-button>
            <a-empty v-if="treeData.length<=0" style="margin-top:20px;"/>
            <a-tree :tree-data="treeData"
                    style="margin-top:20px;"
                    :defaultExpandAll="true"
                    checkable
                    @check="oncheck"
                    :replaceFields="replaceFields"/>
        </a-modal>
        <Delete ref="del" :dalete="dalete" @confirm="delIsok"/>
        <Delete ref="delA" :dalete="daleteA" @confirm="delIsokA"/>
    </div>
</template>

<script>
    import Headline from "@/components/Headline";
    import {getDevAreaTree} from "@/api/perUnit";
    import Delete from "@/components/Delete";
    import {Setperms} from "@/assets/js/setperms";
    import {delUserArea, getAreaUserList, getUserAreaList, getUserList, saveUserArea,} from "@/api/systemmanagement";

    export default {
        name: "AreaAccredit",
        components: {Headline, Delete},
        data() {
            return {
                selectedKeys: [],
                dalete: {
                    titles: this.$t("m.DeleteThePrompt"),
                    type: "exclamation-point",
                    text: this.$t("m.AreYouSureToDeleteThisData"),
                },
                daleteA: {
                    titles: this.$t("m.DeleteThePrompt"),
                    type: "exclamation-point",
                    text: this.$t("m.AreYouSureToDeleteThisData"),
                },
                selectedRowKeysList: [],
                forminitial: {
                    start: 0,
                    limit: 10,
                    key: "",
                    page: 1,
                    areaCode: "",
                },
                data: [],
                defaultSelect: "",
                dataA: [],
                columns: [
                    {title: this.$t("m.AdministratorName"), dataIndex: "nickname"},
                    {title: this.$t("m.privilegedperson"), dataIndex: "creator"},
                    {title: this.$t("m.privilegedTime"), dataIndex: "createdate"},
                    {
                        title: this.$t("m.Operation"),
                        key: "tags",
                        scopedSlots: {customRender: "tags"},
                    },
                ],
                total: 0,
                visible: false,
                areaValue: "",
                columnsB: [
                    {
                        title: this.$t("m.Code"),
                        dataIndex: "usercode",
                    },
                    {
                        title: this.$t("m.Name"),
                        dataIndex: "nickname",
                    },
                ],
                dataB: [],
                forminitialA: {
                    start: 0,
                    limit: 10,
                    key: "",
                    page: 1,
                },
                totalA: 0,
                forminitialB: {
                    userIds: "",
                    areaCode: "",
                    isChild: 0,
                },
                visibleB: false,
                treeData: [],
                replaceFields: {children: "children", title: "areaname", key: "userareaid"},
                delId: "",
                forminitialC: {
                    userId: '',
                    key: ''
                },
            };
        },
        created() {
            this.getDevAreaTreeList();
            this.parms = Setperms(
                this.$route.fullPath,
                JSON.parse(sessionStorage.getItem("menu"))
            );
            console.log(this.parms);
        },
        methods: {
            onSearchA() {
                getUserAreaList({params: this.forminitialC})
                    .then((res) => {
                        console.log(res);
                        this.treeData = res.data;
                    })
                    .then((err) => {
                        console.log(err);
                    });
            },
            delIsokA() {
                delUserArea({ids: this.selectedKeys.join(',')})
                    .then((res) => {
                        console.log(res);
                        if (res.data.success == true) {
                            this.$message.success(res.data.msg);
                            this.onSearchA();

                        }
                        if (res.data.success == false) {
                            this.$message.warning(res.data.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.error("操作失败");
                    });
                this.$refs.delA.visible = false
            },
            del() {
                if (this.selectedKeys.length <= 0) return this.$message.warning('请勾选部门')
                this.$refs.delA.visible = true
            },
            oncheck(checkedKeys, info) {
                console.log(checkedKeys);
                this.selectedKeys = checkedKeys;
            },
            isTrue(str) {
                return this.parms.indexOf(str) !== -1;
            },
            delkey(text, tags, i) {
                this.delId = tags.id;
                this.$refs.del.visible = true;
                console.log(tags);
            },
            handleChange(e) {
                this.forminitialC.userId = e
                getUserAreaList({params: this.forminitialC})
                    .then((res) => {
                        console.log(res);
                        this.treeData = res.data;
                    })
                    .then((err) => {
                        console.log(err);
                    });
            },
            handleCancelB() {
                this.forminitialC.userId = ''
                this.treeData = []
                this.visibleB = false;
            },
            inquire() {
                this.visibleB = true;
                this.getuserlist();
            },
            delIsok() {
                delUserArea({ids: this.delId})
                    .then((res) => {
                        console.log(res);
                        if (res.data.success == true) {
                            this.$message.success(res.data.msg);
                            this.getAreaUserListAll();
                        }
                        if (res.data.success == false) {
                            this.$message.warning(res.data.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.error("操作失败");
                    });
                this.$refs.del.visible = false;
            },
            delitem(text, tags, i) {
                // this.delId = tags.userid
                // this.$refs.del.visible = true
                // console.log(tags.userid);
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                // this.dataList = selectedRows[0];
                this.forminitialB.userIds = selectedRows[0].userid;
                this.selectedRowKeysList = selectedRowKeys;
                console.log(this.selectedRowKeysList);
            },
            handleOk() {
                if (this.forminitialB.userIds == "")
                    return this.$message.warning("请选择系统管理员");
                saveUserArea(this.forminitialB)
                    .then((res) => {
                        console.log(res);
                        if (res.data.success == true) {
                            this.getAreaUserListAll();
                            this.$message.success(res.data.msg);
                        }
                        if (res.data.success == false) {
                            this.$message.warning(res.data.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.error("操作失败");
                    });
                this.selectedRowKeysList = [];
                this.visible = false;
                // console.log(this.forminitialB)
            },
            onSearch(value) {
                this.getuserlist();
            },
            onChange(e) {
                if (e.target.checked == true) {
                    this.forminitialB.isChild = 1;
                }
                if (e.target.checked == false) {
                    this.forminitialB.isChild = 0;
                }
            },
            onShowSizeChangeA(page, limit) {
                this.forminitialA.page = page;
                this.forminitialA.limit = limit;
                this.getuserlist();
            },
            PagesA(page, pageSize) {
                this.forminitialA.limit = pageSize;
                this.forminitialA.page = page;
                this.forminitialA.start = (page - 1) * pageSize;
                this.getuserlist();
            },
            getuserlist() {
                getUserList({params: this.forminitialA})
                    .then((res) => {
                        this.dataB = res.data.data;
                        this.totalA = res.data.total;
                        console.log(res.data.data);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            add() {
                this.visible = true;
                this.getuserlist();
            },
            handleCancel() {
                this.visible = false;
            },
            onShowSizeChange(page, limit) {
                this.forminitial.page = page;
                this.forminitial.limit = limit;
                this.getAreaUserListAll();
            },
            Pages(page, pageSize) {
                this.forminitial.limit = pageSize;
                this.forminitial.page = page;
                this.forminitial.start = (page - 1) * pageSize;
                this.getAreaUserListAll();
            },
            argumentSelect(value, key, extra) {
                this.forminitial.areaCode = extra.triggerNode.$attrs.cont.areacode;
                this.areaValue = extra.triggerNode.$attrs.cont.areaname;
                this.forminitialB.areaCode = extra.triggerNode.$attrs.cont.areacode;
                this.getAreaUserListAll();
                // console.log(extra.triggerNode.$attrs.cont.areacode);
            },
            getAreaUserListAll() {
                getAreaUserList({params: this.forminitial})
                    .then((res) => {
                        this.dataA = res.data.data;
                        this.total = res.data.total;
                        console.log(res.data.data);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            getDevAreaTreeList() {
                getDevAreaTree()
                    .then((res) => {
                        this.defaultSelect = res.data[0].areaname;
                        this.areaValue = res.data[0].areaname;
                        this.data = res.data;
                        this.forminitial.areaCode = res.data[0].areacode;
                        this.forminitialB.areaCode = res.data[0].areacode;
                        this.getAreaUserListAll();
                        // console.log(res.data[0].areacode)
                        // console.log(res.data[0]);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
        },
    };
</script>

<style>
</style>
